
package org.zjx.config;

import com.alibaba.fastjson2.JSON;
import org.zjx.core.DecisionNode;
import org.zjx.core.DecisionTree;
import org.zjx.core.DefaultDecisionTree;

import java.io.InputStream;
import java.util.Map;

/**
 * 决策树JSON配置加载器
 */
public class DecisionConfig {

    /**
     * 从JSON文件加载决策树配置
     */
    public static DecisionTree loadFromJson(String configPath,
                                            Map<String, DecisionNode> nodeRegistry) {
        try (InputStream is = DecisionConfig.class.getResourceAsStream(configPath)) {
            ConfigDefinition def = JSON.parseObject(is, ConfigDefinition.class);
            assert def != null;
            return buildTree(def, nodeRegistry);
        } catch (Exception e) {
            throw new RuntimeException("Failed to load decision config: " + configPath, e);
        }
    }

    private static DecisionTree buildTree(ConfigDefinition def,
                                          Map<String, DecisionNode> nodeRegistry) {
        DecisionNode root = nodeRegistry.get(def.rootNode);
        if (root == null) {
            throw new IllegalArgumentException("Unknown root node: " + def.rootNode);
        }
        return new DefaultDecisionTree(root);
    }

    // JSON配置结构
    private static class ConfigDefinition {
        public String name;
        public String rootNode;
        public Map<String, String> nodeLinks;
    }
}